package com.peanut.baby.mvp.liveroom;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.model.LiveMsg;
import com.peanut.baby.model.LiveRoom;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.widget.VoiceRecorderView;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by anonymouslystudio on 2017/7/17.
 */

public class RoomLectureFragment extends BaseMessageFragment implements View.OnClickListener,
        TextView.OnEditorActionListener,View.OnTouchListener,LiveRoomMessageAdapter.OnAudioPlayFinishedListener {
    private static final String TAG = RoomLectureFragment.class.getSimpleName();

    @BindView(R.id.liveroom_lecture_recycler)
    RecyclerView recycler;
    @BindView(R.id.lecture_edit)
    EditText edit;
    @BindView(R.id.lecture_voice)
    ImageView voice;
    @BindView(R.id.lecture_album)
    ImageView album;
    @BindView(R.id.lecture_camera)
    ImageView camera;
    @BindView(R.id.lecture_input_container)
    LinearLayout inputContainer;
    Unbinder unbinder;
    @BindView(R.id.voice_recorder)
    VoiceRecorderView voiceRecorder;
    @BindView(R.id.btn_press_to_speak)
    LinearLayout pressToSpeak;
    @BindView(R.id.view_switcher)
    ViewSwitcher viewSwitcher;

    private AutoScrollListener     autoScrollListener;

    private LiveRoomMessageAdapter adapter;
    List<LiveMsg> messages;

    private LinearLayoutManager layoutManager;

    private LiveRoom    room;

    public static RoomLectureFragment newInstance(LiveRoom room) {
        RoomLectureFragment fg = new RoomLectureFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("room",room);
        fg.setArguments(bundle);
        return fg;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_liveroom_lecture, null);
        unbinder = ButterKnife.bind(this, rootView);

        edit.setOnEditorActionListener(this);
        album.setOnClickListener(this);
        voice.setOnClickListener(this);
        camera.setOnClickListener(this);
        pressToSpeak.setOnTouchListener(this);
        voiceRecorder.setVoicePath(InitManager.getInstance().getVoiceDir());
        return rootView;
    }

    private boolean isHoster(){
        Log.d(TAG,"isHoster: uid "+InitManager.getInstance().getUserId());
        if(InitManager.getInstance().getUserId().equals(room.expertId)
                || InitManager.getInstance().getUserId().equals(room.serverId)){
            return true;
        }
        return false;
    }

    @Override
    public void initData() {
        room = (LiveRoom) getArguments().getSerializable("room");
        Log.d(TAG,"initData.."+room.toString());
        inputContainer.setVisibility(isHoster() ? View.VISIBLE:View.GONE);
        layoutManager = new LinearLayoutManager(getActivity());
        adapter = new LiveRoomMessageAdapter(getMessages());
        recycler.setLayoutManager(layoutManager);
        recycler.setAdapter(adapter);
        adapter.setOnAudioPlayFinishedListener(this);
    }

    @Override
    public void onMessageGet(List<LiveMsg> newMsgs) {
        super.onMessageGet(newMsgs);
        getMessages().addAll(newMsgs);
        if (isActive() && adapter != null) {
            adapter.notifyDataSetChanged();
            recycler.scrollToPosition(adapter.getItemCount()-1);
        }
    }

    private List<LiveMsg> getMessages() {
        if (messages == null) {
            messages = new ArrayList<>();
        }

        return messages;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lecture_voice:
                switchInputType();
                break;
            case R.id.lecture_album:
                onPictureClicked();
                break;
            case R.id.lecture_camera:
                onCameraClicked();
                break;
        }
    }

    private void switchInputType(){
        viewSwitcher.showNext();
        if(viewSwitcher.getCurrentView() ==pressToSpeak){
            onVoiceClicked();
        }

    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        Log.d(TAG, "actionId: " + actionId);
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendTextMessage();
            return true;
        }
        return false;
    }

    /**
     *
     */
    private void sendTextMessage() {
        String text = edit.getText().toString().trim();
        if (TextUtils.isEmpty(text)) {
            showToast("请输入要发送的内容");
            return;
        }
        sendTextMessage(LiveMsg.TAB_LECTURE, text);
    }

    public void onSendMessageSuccess() {
        edit.setText("");
    }


    public void onPictureUploadSuccess(UploadConf config) {
        sendPictureMessage(LiveMsg.TAB_LECTURE, config.getResultFullUrl(), config.localPath);
    }

    public void onAudioUploadSuccess(UploadConf config) {
        sendVoiceMessage(LiveMsg.TAB_LECTURE, config.getResultFullUrl(), config.duration);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return voiceRecorder.onPressToSpeakBtnTouch(v, event, new VoiceRecorderView.VoiceRecorderCallback() {
            @Override
            public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                onRecordFinished(voiceFilePath,voiceTimeLength);
            }
        });
    }

    @Override
    public void onAudioPlayFinished(int position) {
        //try to  play next audio
        //if last message , return
        Log.d(TAG,"onAudioPlayFinished2 "+ position);

        if(position >= messages.size() - 1){
            return;
        }
        //
        for(int i= position+1;i<=messages.size() - 1;i++){
            LiveMsg msg = messages.get(i);
            if(msg.messageType == LiveMsg.TYPE_VOICE){
                autoPlayNextVoice(i);
                break;
            }
        }
    }

    /**
     * auto play next voice
     * @param nextPosition  next voice message position
     */
    private void autoPlayNextVoice(int nextPosition){
        Log.d(TAG,"autoPlayNextVoice nextPosition  "+nextPosition);
        autoScrollListener = new AutoScrollListener(nextPosition);
        recycler.addOnScrollListener(autoScrollListener);
        recycler.smoothScrollToPosition(nextPosition);

        int firstVisiblePos =  ((LinearLayoutManager) recycler.getLayoutManager()).findFirstVisibleItemPosition();
        Log.d(TAG,"firstVisiblePos "+firstVisiblePos);
        View v = recycler.getChildAt(nextPosition - firstVisiblePos);
        Log.d(TAG,"autoPlayNextVoice2 "+ (v == null));
        if(v != null){
            v.findViewById(R.id.bubble).performClick();
            recycler.removeOnScrollListener(autoScrollListener);
            autoScrollListener = null;
        }
    }

    class AutoScrollListener extends RecyclerView.OnScrollListener{
        private int nextPosition;
        public AutoScrollListener(int nextPosition){
            this.nextPosition = nextPosition;
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if(newState == RecyclerView.SCROLL_STATE_IDLE){
                Log.d(TAG,"onScrollStateChanged");
                View itemView = layoutManager.findViewByPosition(nextPosition);
                if(itemView != null){
                    itemView.findViewById(R.id.bubble).performClick();
                    recycler.removeOnScrollListener(autoScrollListener);
                    autoScrollListener = null;
                }
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
        }
    }

}
